package pt.fct.mpc.lastfm;

import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothActivity;
import pt.fct.mpc.lastfm.connectivity.bt.LastfmBluetoothManager;
import pt.fct.mpc.lastfm.database.LastfmDatabaseAdapter;
import pt.fct.mpc.lastfm.geo.LastfmGeoEventsActivity;
import pt.fct.mpc.lastfm.search.LastfmSearchActivity;
import pt.fct.mpc.lastfm.user.LastfmFavouritesActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {

	private static final String TAG = "Last.fm Main Activity";
	private static MainActivity instance;

	@SuppressWarnings("unused")
	private static SharedPreferences lastfm_persistent_prefs;
	private static SharedPreferences lastfm_temporary_prefs;

	private OnClickListener listener_button_search = new OnClickListener() {
		@Override
		public void onClick(View v) {
			if (dialog_search != null)
				dialog_search.show();
		}
	};

	private OnClickListener listener_button_geo_events = new OnClickListener() {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(v.getContext(),
					LastfmGeoEventsActivity.class);
			startActivity(intent);
		}
	};

	private OnClickListener listener_button_favourites = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(v.getContext(),
					LastfmFavouritesActivity.class);
			startActivity(intent);
		}
	};

	private AlertDialog dialog_search = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		instance = this;

		Log
				.d(TAG, "Calling onCreate(); saved instance = "
						+ savedInstanceState);

		requestWindowFeature(Window.FEATURE_NO_TITLE);

		LastfmDatabaseAdapter.getInstance(getApplicationContext());
		LastfmBluetoothManager.initialize(getApplicationContext());

		initiatePreferences();

		setContentView(R.layout.lastfm_main);

		Button button_search = (Button) findViewById(R.id.layout_main_button_search);
		Button button_geo_events = (Button) findViewById(R.id.layout_main_button_geo_events);
		Button button_favourites = (Button) findViewById(R.id.layout_main_button_favourites);

		button_search.setOnClickListener(listener_button_search);
		button_geo_events.setOnClickListener(listener_button_geo_events);
		button_favourites.setOnClickListener(listener_button_favourites);

		createSearchDialog();
	}

	@Override
	protected void onPause() {
		super.onPause();
		Log.d(TAG, "Calling onPause()");
	}

	@Override
	protected void onStop() {
		super.onStop();
		Log.d(TAG, "Calling onStop()");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "Calling onResume()");

		checkConnectivity();
		
		Button button_search = (Button) findViewById(R.id.layout_main_button_search);
		Button button_geo_events = (Button) findViewById(R.id.layout_main_button_geo_events);

		boolean buttons_visible = true;
		if ((isConnectable() == false) 
			&& (LastfmBluetoothManager.isOn() == false)) 
		{
			buttons_visible = false;
		}
		button_search.setEnabled(buttons_visible);
		button_geo_events.setEnabled(buttons_visible);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.lastfm_options_menu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem bt_on = menu.findItem(R.id.lastfm_options_menu_item_gw_bt_on);
		MenuItem bt_off = menu
				.findItem(R.id.lastfm_options_menu_item_gw_bt_off);

		// default behavior.
		boolean bt_on_visibility = true, bt_off_visibility = false;

		boolean status = lastfm_temporary_prefs.getBoolean(
				LastfmPreferences.Temporary.PREF_BT_GW, false);

		Log.d(TAG, "BT status = " + status);

		if (status) {
			bt_on_visibility = false;
			bt_off_visibility = true;
		}
		bt_on.setVisible(bt_on_visibility);
		bt_off.setVisible(bt_off_visibility);

		Log.d(TAG, "BT menu: ON = " + bt_on.isVisible() + "; OFF = "
				+ bt_off.isVisible());

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent;

		boolean ret = true;
		switch (item.getItemId()) {
		case R.id.lastfm_options_menu_item_preferences:

			break;

		case R.id.lastfm_options_menu_item_gw_bt_on:
			enableBluetooth();
			break;

		case R.id.lastfm_options_menu_item_gw_bt_off:

			setTemporaryPreference(LastfmPreferences.Temporary.PREF_BT_GW,
					false);
			break;

		case R.id.lastfm_options_menu_item_about:

			intent = new Intent(getApplicationContext(),
					LastfmAboutActivity.class);

			startActivityForResult(intent, 0);

			break;
		}

		return ret;
	}

	static public void setTemporaryPreference(String pref_name, boolean b) {
		Editor editor = lastfm_temporary_prefs.edit();

		editor.remove(pref_name);
		editor.putBoolean(pref_name, b);
		editor.commit();
	}

	public boolean hasAnyConnection() {
		return (isConnectable() || lastfm_temporary_prefs.getBoolean(
				LastfmPreferences.Temporary.PREF_BT_GW, false));
	}

	public boolean isConnectable() {
		ConnectivityManager connectivity_manager = 
			(ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);

		NetworkInfo network_info = connectivity_manager.getActiveNetworkInfo();

		return (network_info != null);
	}

	private void enableBluetooth() {
		setTemporaryPreference(LastfmPreferences.Temporary.PREF_BT_GW, true);

		Intent intent = new Intent(getApplicationContext(),
				LastfmBluetoothActivity.class);

		startActivityForResult(intent, 0);
	}

	private void checkConnectivity() {
		if ((isConnectable()) || (LastfmBluetoothManager.isOn()))
			return;

		DialogInterface.OnClickListener listener_enable_bt = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				enableBluetooth();
			}
		};

		DialogInterface.OnClickListener listener_no_bt = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				Toast.makeText(getApplicationContext(),
						"Most application features won't be enabled.",
						Toast.LENGTH_LONG).show();
			}
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("No Connectivity").setMessage(
				"Your application has no WIFI or 3G access. "
						+ "Do you want to enable Bluetooth access?")
				.setPositiveButton("Yes", listener_enable_bt)
				.setNegativeButton("No", listener_no_bt);

		AlertDialog alert_dialog = builder.create();
		alert_dialog.show();
	}

	private void initiatePreferences() {
		lastfm_persistent_prefs = getSharedPreferences(
				LastfmPreferences.PERSISTENT_FILE_NAME, Context.MODE_PRIVATE);

		lastfm_temporary_prefs = getSharedPreferences(
				LastfmPreferences.TEMPORARY_FILE_NAME, Context.MODE_PRIVATE);

		Editor lastfm_temp_prefs_editor = lastfm_temporary_prefs.edit();
		lastfm_temp_prefs_editor.clear();
		lastfm_temp_prefs_editor.commit();
	}

	private void createSearchDialog() {
		final CharSequence[] items = { "Artists", "Albums" };

		AlertDialog.Builder builder = new AlertDialog.Builder(this);

		builder.setTitle("Choose Search Type");
		builder.setItems(items, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int item) {

				int search_type = LastfmSearchActivity.SEARCH_ARTIST;

				switch (item) {
				case 0: // Artists
					search_type = LastfmSearchActivity.SEARCH_ARTIST;
					break;
				case 1: // Albums
					search_type = LastfmSearchActivity.SEARCH_ALBUM;
					break;
				}

				Bundle search_params = new Bundle();
				search_params.putInt("type", search_type);

				Intent intent = new Intent(getApplicationContext(),
						LastfmSearchActivity.class);
				intent.putExtras(search_params);

				startActivityForResult(intent, 0);
			}
		});

		dialog_search = builder.create();

	}

	public static SharedPreferences getLastfmTemporaryPreferences() {
		return lastfm_temporary_prefs;
	}

	public static MainActivity getInstance() {
		return instance;
	}
}